<?php

header("Content-type: text/html; charset=utf-8");
include_once('Logging.php');

class SLWExpressClass{
    const SERVER_KEY_TEST = 'a83cdbffb8164b85a828cfcf97390871';
    const SERVER_KEY = '';

    const PWD_TEST = 'yuanzu123';
    const PWD = '';

    const USER365ID_TEST = '13816388429';
    const USER365ID = '';
    const BILL_URL_TEST = 'https://testopen.365paotui.cn/api/';
    const BILL_URL = 'https://openapi.365paotui.cn/api/';

    private $user365Id = '';
    private $isDebug = '';
    public function __construct($isDebug,$user365Id){
        $this->isDebug = $isDebug;
        $this->user365Id = $user365Id;
    }


    /** 用户登录
     * @param $data
     */
    public function userLogin($data){
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'userLogin.do';
        $parameter = [
            'user365Id' => $data[0],
            'password' => $data[1],
            'serviceKey' => $data[2],
        ];
//        $result = $this->request_post_token($url, $parameter);
        $result = $this->request_post($url, $parameter);
        $result = json_decode($result, true);
        return $result;
    }


    /** 计价
     * @param $data
     */
    public function expressCost($data){
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'expressCost.do';
        $parameter = [
            'senderAddressLon' => $data['deliver_lng'],                                                    # 发货地坐标经度
            'senderAddressLat' => $data['deliver_lat'],                                                    # 发货地坐标纬度
            'weight' => $data['actual_weight'],                                                            # 重量单位公斤
            'transportation' => 1600,                                                                      # 配送工具 有效值：1600（其他） 1601（汽车）
            'appointmentTime' => $data['shop_delivery_time'],                                              # 预约时间 日期格式yyyy-MM-dd HH:mm:ss
            'token' => $data['token'],                                                                     # 访问凭证
        ];

        if($data['slat'] && $data['slng']){
            $parameter['receiverAddressLon'] = $data['slng'];          # 收货地坐标经度
            $parameter['receiverAddressLat'] = $data['slat'];          # 收货地坐标纬度
        }else{
            $parameter['receiverAddressLon'] = $data['lng'];
            $parameter['receiverAddressLat'] = $data['lat'];
        }

        $result = $this->request_post($url, $parameter);
        $result = json_decode($result, true);
        return $result;
    }

    /** 推送订单
     * @param $data
     */
    public function createOrder($data){
        $user365Id = (($this->isDebug) ? self::USER365ID_TEST : ($this->user365Id));
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'createOrder.do';
        $parameter = [
            'user365Id' => $user365Id,                                                                                          # 金额令牌，计算订单价格接口返回的price_token
            'appointmentTime' => $data['shop_delivery_time'],                                                                   # 订单预约时间 日期格式yyyy-MM-dd HH:mm:ss
            'orderNote' => $data['shop_express_remark'],                                                                        # 订单备注 最大长度50字符
            'goodsName' => $data['products'][0]['product_name'],                                                                # 寄送物品名称 最大长度30字符
            'goodsWeight' => $data['actual_weight'],                                                                            # 寄送物品重量 单位公斤，正整数
            'senderName' => $data['shop_name'],                                                                                 # 发货人姓名 最大长度30字符
            'senderPhone' =>  $data['deliver_phone'],                                                                           # 发货人电话 手机号、座机号（010-12345678）
            'senderAddress' =>  $data['deliver_province'].$data['deliver_city'].$data['deliver_area'].$data['deliver_address'],                  # 发货人地址 即地图上经纬度对应的地址，最大长度150字符
            'senderAddressDetail' => $data['deliver_province'].$data['deliver_city'].$data['deliver_area'].$data['deliver_address'],             # 发货人详细地址 收货的详细地址，可细化到街道、小区、楼号、门牌号，最大长度80字符收货人详细地址
            'senderAddressLon' =>  $data['deliver_lng'],                                                                        # 发货地址经度
            'senderAddressLat' =>  $data['deliver_lat'],                                                                        # 发货地址纬度

            'receiverName' =>  $data['receiver'],                                                                               # 收货人姓名 最大长度30字符
            'receiverPhone' =>  $data['receiver_tel'],                                                                          # 收货人电话 手机号、座机号（010-12345678）
            'receiverAddress' => $data['receiver_address'],                                                                     # 收货人地址 即地图上经纬度对应的地址，最大长度150字符
            'receiverAddressDetail' => $data['receiver_address'],                                                               # 收货的详细地址，可细化到街道、小区、楼号、门牌号，最大长度80字符
//            'receiverAddressLon' => $data['lng'],                                                                               # 收货人地址经度
//            'receiverAddressLat' => $data['lat'],                                                                               # 收货人地址纬度

            'transportation' => 1600,                                                                                           # 配送工具 1600：其他 1601：汽车
            'totalCost' => $data['totalCost'],                                                                                  # 总运费 计算运费时返回的totalCost
            'tpOrderId' => $data['shop_express_no'],                                                                            # 第三方订单号,推送可以回传
            'token' => $data['token'],
        ];


        if($data['slat'] && $data['slng']){
            $parameter['receiverAddressLon'] = $data['slng'];          # 收货地坐标经度
            $parameter['receiverAddressLat'] = $data['slat'];          # 收货地坐标纬度
        }else{
            $parameter['receiverAddressLon'] = $data['lng'];
            $parameter['receiverAddressLat'] = $data['lat'];
        }
        $result = $this->request_post($url, $parameter);
        $result = json_decode($result, true);
        return $result;
    }


    /**
     *  经纬度
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function orderLocation($data){
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'orderLocation.do';
        $parameter = [
            'orderId' => $data['orderId'],
            'token' => $data['token'],
        ];
        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }

    /**
     * 取消订单
     * @return string
     * @param $post 数组参数 CANCEL_TEST
     */
    public function cancelOrder($data){
        $url = (($this->isDebug) ? self::BILL_URL_TEST : (self::BILL_URL)).'cancelCall.do';
        $parameter = [
            'orderId' => $data['orderId'],                       # 订单ID
            'token' => $data['token'],
        ];
        $result = $this->request_post($url, $parameter);
        if (!empty($result)){
            $result = json_decode($result, true);
        }
        return $result;
    }


    /**
     * 发起http post请求
     */
    private function request_post($url, array $post_data){
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $log = new Logging();
        $log->lfile('slw_express');

        $time = strtotime(date('Y-m-d H:i:s'));
        $log->lwrite('url: ' . $url);
        $log->lwrite($time.': ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)));

        $arr = [];
        foreach ($post_data as $key => $value) {
            $arr[] = $key . '=' . $value;
        }

        $curlPost = implode('&', $arr);
        $log->lwrite($time.'FORM-DATA: ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)));
        $postUrl = $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);
        curl_close($ch);
        $log->lwrite($time . ',' . json_encode(json_decode($data, true), JSON_UNESCAPED_UNICODE));
        return $data;
    }

//    private function request_post_token($url, array $post_data){
//        if (empty($url) || empty($post_data)) {
//            return false;
//        }
//        $time = strtotime(date('Y-m-d H:i:s'));
//        file_put_contents('../../logs/slw_token.log','request__'.$time.': ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)),FILE_APPEND);
//
//        $arr = [];
//        foreach ($post_data as $key => $value) {
//            $arr[] = $key . '=' . $value;
//        }
//
//        $curlPost = implode('&', $arr);
//        file_put_contents('../../logs/slw_token.log','request__'.$time.'FORM-DATA: ' . (json_encode($post_data,JSON_UNESCAPED_UNICODE)),FILE_APPEND);
//        $postUrl = $url;
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $postUrl);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
//        $data = curl_exec($ch);
//        curl_close($ch);
//        file_put_contents('../../logs/slw_token.log','request__'.$time . ',' . json_encode(json_decode($data, true),FILE_APPEND));
//
//        return $data;
//    }

}